<template>
  <div class="wrapper">
    <FormPanel
      ref="formPanel"
      :list="inputs"
      labelWidth="150"
      :formType="type"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
    />

    <!-- table -->
    <div v-show="disabled">
      <FilterTable
        height="300"
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :isSelectColumn="isSelectColumn"
        :params="flterValue"
        :isToperInfo="false"
        :datakey="'records'"
        :onColumnsChange="columns => this.columns = columns"
        columnsRef="projectOperating_material_oemReview_info_01"
      >
        <template slot="controls">
          <el-button
            :disabled="type === 'edit'"
            size="small"
            type="primary"
            icon="el-icon-plus"
            @click="dealerHandle"
          >添加经销商</el-button>
        </template>
      </FilterTable>
    </div>

    <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-madal
        ref="addDialogRef"
        selectType="multiple"
        v-model="initDealerData"
        :deptId="orgId"
        :dealerType="dealerType"
        @close="closeDealer"
      />
    </BaseDialog>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button :loading="xfLoading" type="primary" @click="xfDialog">下 发</el-button>
      <el-button :loading="bhLoading" type="primary" @click="bhDialog">驳 回</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dealerMadal from '@/pages/cms-common/dealerdata/dealerType';
// import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire'; //获取登录信息
import { getDealers, getmaterialTypeOneList, saveMaterials, updateMaterial, updateXFMaterial, selectMaterialListByBill } from '@/api/cms-api/projectOperating/program/push';
import { searchRegionalDealerManager } from '@/api/cms-api/origin/personnelInfo/areaMaintain';
export default {
  mixins: [dictionary],
  components: { dealerMadal },
  props: {
    type: {
      type: String,
      required: true
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  mounted() {
    // console.log(this.value);
  },
  data() {
    return {
      inputs: this.getInputs(),
      inputsData: {},
      formValue: {},
      dataParams: {}, //父类参数
      caseUrlList: [],
      columns: this.creatHeader(),
      dataSource: [],
      isSelectColumn: false,
      flterValue: {}, //参数
      initDealerData: {}, //经销商弹窗参数
      visibleDealer: false,
      disabled: false, //是否可以添加经销商
      xfLoading: false,
      bhLoading: false,
      orgUrls: [],
      orgId: null, //登录人所属组织
      dealerType: '25381001,25381002,25381003,25381004,25381005' //不包含大客户的
    };
  },
  created() {
    this.init();
    // this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      this.loginUser = await getLoginUser({});
      if (this.loginUser.data.orgType == 15061005) {
        //是事业部
        this.orgId = this.loginUser.data.orgId;
      }
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      // this.dataSource = data.data;
      this.addSelectDealer(data.data);
      this.visibleDealer = data.visible; //关闭弹窗
    },
    //添加选择经销商到列表中
    addSelectDealer(dealers) {
      if (dealers != null && typeof dealers != 'undefined' && dealers.length > 0)
        dealers.forEach(dealer => {
          let dealerCode = dealer.dealerCode;
          if (!this.isExistInDatasouce(dealerCode)) {
            let dealerNode = {
              deptName: '',
              dealerName: dealer.dealerName,
              ownerCode: dealer.dealerCode,
              dealerId: null,
              dealerShortname: dealer.dealerShortname,
              shopLevel: dealer.shopLevel,
              relationId: -1,
              managerId: 1,
              cityId: dealer.cityId,
              provinceId: dealer.provinceId,
              districtId: dealer.districtId,
              isDeleted: '0',
              majorManagerId: null,
              dealerType: 25031001
            };
            this.dataSource.push(dealerNode);
          }
        });
    },
    //判断经销商是否已经在列表中选择
    isExistInDatasouce(dealerCode) {
      let r = false;
      if (this.dataSource && this.dataSource.length > 0) {
        for (let dIdx = 0; dIdx < this.dataSource.length; dIdx++) {
          let tcode = this.dataSource[dIdx].ownerCode;
          if (tcode == dealerCode) {
            r = true;
            break;
          }
        }
      }
      return r;
    },
    // 经销商打开窗口 -传数据
    dealerHandle() {
      this.initDealerData = {
        excludeBigCustomer: false, //是否查询大客户经销商，如果查询 true，不查询 false
        id: 1001
      };
      this.visibleDealer = true;
    },
    //搜索获取数据
    changeHandle(val) {
      this.flterValue = val;
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props, h) => {
            return (
              <div>
                <el-button disabled size="mini" type="text" onClick={() => this.editHandle(props.$index)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '公司全称', dataIndex: 'dealerName', sorter: true },
        { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
        { title: '经销商简称', dataIndex: 'dealerShortname', sorter: true }
      ];
    },
    //列表删除
    // editHandle(row) {
    //   this.dataSource.splice(row.index, 1);
    // },
    editHandle(index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dataSource.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    async init() {
      if (this.type === 'edit') {
        // 更新接口需要的记录 ID
        this.materialId = this.rowData.materialId;
        this.materialStatus = this.rowData.materialStatus;
        this.ownerCode = this.rowData.ownerCode;
        this.sourceDept = this.rowData.sourceDept;
        // console.log(this.rowData);
        //初始化二级
        this.initmaterialTypeTwo(this.rowData.materialTypeOne);
        //初始化三级
        this.initmaterialTypeThree(this.rowData.materialTypeTwo);
        //初始化四级
        this.initmaterialTypeFour(this.rowData.materialTypeThree);
        //初始化五级
        this.initmaterialTypeFive(this.rowData.materialTypeFour);
        //大附件
        let res = {};
        let fileParams = { materialId: this.materialId, billType: 25721003 };
        res = await selectMaterialListByBill(fileParams);
        if (res.data.length > 0) {
          for (let j = 0; j < res.data.length; j++) {
            this.orgUrls.push(res.data[j].fileId);
          }
        }
        //获取所选要下发的经销商
        if (this.rowData.isNetworkIssued == 10041002) {
          //非全网下发
          let resDealer = {};
          let dealerParams = { materialId: this.materialId };
          resDealer = await getDealers(dealerParams);
          console.log(resDealer);
          if (resDealer.resultCode == 200) {
            if (resDealer.data.length > 0) {
              let resDealerList = [];
              resDealer.data.forEach(x => {
                let dealer = {};
                dealer.dealerName = x.dealerName;
                dealer.ownerCode = x.dealerCode;
                dealer.dealerShortname = x.dealerShortname;
                resDealerList.push(dealer);
              });
              this.dataSource = resDealerList;
            }
          }
        }
        this.inputs.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
          if (x.fieldName == 'reviewIdea') {
            x.initialValue = '';
          }
          if (x.fieldName == 'originalFileUrl') {
            x.initialValue = this.orgUrls;
          }
          if (x.fieldName == 'isNetworkIssued') {
            if (x.initialValue == 10041002) {
              this.disabled = true;
            }
          }
        });
      }
      if (this.type === 'show') {
        this.materialId = this.rowData.materialId;
        this.materialStatus = this.rowData.materialStatus;
        this.inputs.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
      }
    },
    formChangeHandle(val) {
      this.formValue = val;
    },
    getInputs() {
      return [
        {
          type: 'INPUT',
          label: '营销素材代码',
          disabled: true,
          fieldName: 'materialCode',
          placeholder: '系统自动生成',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '营销素材名称',
          disabled: true,
          fieldName: 'materialName',
          placeholder: '',
          initialValue: ''
          // rules: [{ required: true, message: '请输入营销素材名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '来源部门',
          disabled: true,
          fieldName: 'orgName',
          placeholder: '',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '营销素材类型-一级',
          disabled: true,
          fieldName: 'materialTypeOne',
          placeholder: '',
          //           request:{
          //                   fetchApi:getmaterialTypeOneList,
          //                   params:{},
          //                   valueKey:'materialTypeId',
          //                   textKey:'materialTypeName'},
          itemList: [],
          change: value => {
            this.initmaterialTypeTwo(value);
          }
          // rules: [{ required: true, message: '请选择营销素材类型-一级', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '营销素材类型-二级',
          disabled: true,
          fieldName: 'materialTypeTwo',
          placeholder: '',
          itemList: [],
          change: value => {
            this.initmaterialTypeThree(value);
          }
          // rules: [{ required: true, message: '请选择营销素材类型-二级', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '营销素材类型-三级',
          disabled: true,
          fieldName: 'materialTypeThree',
          placeholder: '',
          itemList: [],
          change: value => {
            this.initmaterialTypeFour(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-四级',
          disabled: true,
          fieldName: 'materialTypeFour',
          placeholder: '',
          itemList: [],
          change: value => {
            this.initmaterialTypeFive(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-五级',
          disabled: true,
          fieldName: 'materialTypeFive',
          placeholder: '',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '使用场景',
          disabled: true,
          fieldName: 'usedScenes',
          placeholder: '',
          initialValue: '',
          selfCols: 3
        },
        // {
        //   type: 'SELECT',
        //   label: '营销素材状态',
        //   disabled: true,
        //   fieldName: 'materialStatus',
        //   placeholder: '请选择...',
        //   initialValue: '25361001',
        //   itemList: this.createDictList('2536')
        // },
        {
          type: 'SELECT',
          label: '是否需要反馈',
          disabled: true,
          fieldName: 'isNeedFeedback',
          placeholder: '',
          itemList: this.createDictList('1004')
          // rules: [{ required: true, message: '请选择是否需要反馈', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '反馈截止日期',
          disabled: true,
          fieldName: 'feedbackEndDate',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '',
          itemList: []
          // rules: [{ required: true, message: '请输入反馈截止日期', trigger: 'blur' }]
        },
        {
          type: 'TEXT_AREA',
          label: '原始文件下载地址',
          disabled: true,
          fieldName: 'originalFileUrl',
          placeholder: '',
          initialValue: '',
          selfCols: 3
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件缩略图',
          disabled: true,
          fieldName: 'caseUrl',
          // rules: [{ limit: 1, validator: this.validateFn, message: '最多上传1张', trigger: 'change' }],
          upload: {
            actionUrl: '/api/file/oss/upload'
          }
        },
        {
          type: 'SELECT',
          label: '是否全网下发',
          fieldName: 'isNetworkIssued',
          placeholder: '请选择...',
          disabled: true,
          itemList: this.createDictList('1004')
          // change: this.isAllChange,
          // rules: [{ required: true, message: '请选择是否全网下发', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '创建人',
          disabled: true,
          fieldName: 'createdByName',
          placeholder: '',
          initialValue: '',
          selfCols: 3
        },
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'reviewIdea',
          initialValue: '',
          rows: 4,
          selfCols: 3,
          maxlength: 30
        }
      ];
    },
    //取营销素材类型-一级
    async initmaterialTypeOne() {
      let res = [];
      this.dataParams = { parentTypeId: '' };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[3].itemList = res;
    },
    //取营销素材类型-二级
    async initmaterialTypeTwo(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[4].itemList = res;
    },
    //取营销素材类型-三级
    async initmaterialTypeThree(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[5].itemList = res;
    },
    //取营销素材类型-四级
    async initmaterialTypeFour(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[6].itemList = res;
    },
    //取营销素材类型-五级
    async initmaterialTypeFive(parentTypeId) {
      let res = [];
      this.dataParams = { parentTypeId: parentTypeId };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.inputs[7].itemList = res;
    },
    changeHandle(data) {
      this.inputsData = data;
      this.$emit('close', data);
    },
    //下发
    async xfDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (null == this.$refs.formPanel.SUBMIT_FORM()) {
        return;
      }
      if (this.formValue !== null) {
        let dealerList = [];
        this.dataSource.forEach(x => {
          let dealer = {};
          dealer.dealerId = x.dealerId;
          dealer.dealerName = x.dealerName;
          dealer.ownerCode = x.ownerCode;
          dealerList.push(dealer);
        });
        this.formValue = Object.assign({}, { dealerList: dealerList }, this.formValue);
        // if (this.formValue.isNetworkIssued == 10041002) {
        //   //是全网下发，判断是否添加了经销商
        //   if (this.formValue.dealerList.length == 0) {
        //     this.$notify.warning({ title: '提示信息', message: '请选择添加要下发的经销商!' });
        //     return false;
        //   }
        // }
        this.xfLoading = true;
        //追加隐藏状态字段
        this.formValue = Object.assign({}, { materialStatus: 25361003 }, this.formValue);
        let result = {};
        if (this.formValue.caseUrl != null) {
          for (let i = 0; i < this.formValue.caseUrl.length; i++) {
            this.caseUrlList.push(Object.assign({}, { name: this.formValue.caseUrl[i].name }, { url: this.formValue.caseUrl[i].url }));
          }
          this.formValue = Object.assign({}, { fileUrl: this.caseUrlList }, this.formValue);
        }
        this.formValue = Object.assign({}, { ownerCode: this.ownerCode }, this.formValue);
        this.formValue = Object.assign({}, { sourceDept: this.sourceDept }, this.formValue);
        //大附件地址替换为空
        this.formValue = Object.assign({}, this.formValue, { originalFileUrl: '' });
        result = await updateMaterial(this.formValue, this.materialId);
        if (result.resultCode === 200) {
          this.xfLoading = false;
          this.$notify.success({ title: '提示信息', message: '下发成功!' });
          this.closeDialog('refresh');
        }
      }
    },
    //驳回
    async bhDialog() {
      // this.inputs[13].rules[0].required = false;
      this.$refs.formPanel.SUBMIT_FORM();
      if (null == this.$refs.formPanel.SUBMIT_FORM()) {
        return;
      }
      if (this.formValue != null) {
        //追加隐藏状态字段
        this.formValue = Object.assign({}, { materialStatus: 25361004 }, this.formValue);
        let result = {};
        if (this.type === 'edit') {
          if (this.formValue.caseUrl != null) {
            let caseUrlList1 = [];
            for (let i = 0; i < this.formValue.caseUrl.length; i++) {
              caseUrlList1.push(Object.assign({}, { name: this.formValue.caseUrl[i].name }, { url: this.formValue.caseUrl[i].url }));
            }
            this.formValue = Object.assign({}, { fileUrl: caseUrlList1 }, this.formValue);
          }
          this.formValue = Object.assign({}, { ownerCode: this.ownerCode }, this.formValue);
          this.formValue = Object.assign({}, { sourceDept: this.sourceDept }, this.formValue);
          //大附件地址替换为空
          this.formValue = Object.assign({}, this.formValue, { originalFileUrl: '' });
          console.log(this.formValue);
          if (this.formValue.reviewIdea == null || this.formValue.reviewIdea == '') {
            this.$notify.warning({ title: '提示信息', message: '审核意见必填！且字符限制数量为30！' });
          } else {
            this.bhLoading = true;
            result = await updateMaterial(this.formValue, this.materialId);
            if (result.resultCode === 200) {
              this.bhLoading = false;
              this.$notify.success({ title: '提示信息', message: '已驳回!' });
              this.closeDialog('refresh');
            }
          }
        }
      }
    },
    isAllChange(val) {
      if (val === 10041001) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
    },
    //取消操作
    closeDialog(param) {
      this.$emit('close', false, param);
    }
  },
  mounted() {
    //初始化营销素材类型-一级
    this.initmaterialTypeOne();
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
